package edu.ynu.se.xiecheng.achitectureclass.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.bind.annotation.RequestParam;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

@Entity
@Getter
@Setter
@DiscriminatorValue("4")
public class Business extends User{
    @OneToMany(mappedBy = "business",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties("business")
    private Set<Shop> shops;

    @JsonIgnore
    public Shop addShop(Shop shop){
        shop.setBusiness(this);
        shops.add(shop);
        return shop;
    }

    public Set<Oorder> listOrder(Shop shop){
        Set<Oorder> orders = new HashSet<>();
        Set<ShopItem> shopItems = shop.getShopItems();
        shopItems.forEach(shopItem -> {
            Set<LineItem> lineItems = shopItem.getItem().getLineItems();
            lineItems.forEach(lineItem -> {
                if(lineItem.getOorder().getPayStatus()!=0){
                    orders.add(lineItem.getOorder());
                }
            });
        });
        return orders;
    }

    public Oorder confirmOrder(Shop shop, Oorder oorder){
        AtomicReference<Oorder> result = new AtomicReference<>(null);
        shop.getLineItems().forEach(lineItem -> {
            if(lineItem.getOorder().equals(oorder))
                result.set(oorder);
        });
        result.get().setPayStatus(3);
        return result.get();
    }

    public Oorder refund(Shop shop, Oorder oorder){
        AtomicReference<Oorder> result = new AtomicReference<>(null);
        shop.getLineItems().forEach(lineItem -> {
            if(lineItem.getOorder().equals(oorder))
                result.set(oorder);
        });
        result.get().setPayStatus(4);
        return result.get();
    }

    public Business register(String username, String password){
        this.setUsername(username);
        this.setPassword(password);
        return this;
    }

}
